package controllers;

import helpers.EmailHelper;
import helpers.UrlHelper;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import search.ArticleSearchEngine;
import systems.ConfigSystem;
import systems.Recently;

import entities.Article;
import entities.ArticleSearch;
import entities.SiteConfig;
import entities.User;

import models.ArticleModel;

public class RemoveArticleServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String id = (String) request.getParameter("id");
		String key = (String) request.getParameter("key");
		String action = (String) request.getParameter("action");
		
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = articleModel.getArticle(id);
		
		User user = (User) request.getAttribute("user_logged_in");
		if (action != null && article != null) {
			articleModel.delete(article);
			
			//Set search article
			ArticleSearchEngine.remove(id);
			
			//Remove recently cache
			Recently.remove(article);
			
			//Send email to author
			String serverUrl = UrlHelper.getServerUrl(request);
			String serverName = UrlHelper.getDomainServer(request);
			String emails = user != null ? user.getUsername() : article.getEmail() ;
			String strUrl = serverUrl + "/print-email-delete?id="+article.getId()+"&title=" + article.getTitle();
			String strSubject = "[" + serverName + "] Your article with id " + article.getId() + " has been remove.";
			SiteConfig config = ConfigSystem.getConfigs();
			EmailHelper.sendMailFromUrl(serverName + " <" + config.getContactEmail() + ">", strSubject, strUrl, emails);
			
			article = null;
			request.setAttribute("success", "Article has been removed.");
		}
		
		if (article != null && !article.getAuthKey().equals(key)) {
			article = null;
		}
		
		request.setAttribute("article", article);
		try {
			request.getRequestDispatcher("/pages/remove_article.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
